package com.vrv;

import org.objectweb.asm.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

public class Main3 {


    public static void main(String[] args) throws IOException {
        File inputFile = new File("E:\\projects\\asm\\B.class");
        byte[] bytes = Files.readAllBytes(inputFile.toPath());

        ClassReader classReader = new ClassReader(bytes);
        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
        classReader.accept(new ClassVisitor(Opcodes.ASM9, classWriter) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature,
                                             String[] exceptions) {
                // 修改返回 boolean 的方法 a()
                if ("h".equals(name) && "()Ljava/lang/Boolean;".equals(descriptor) && (access & Opcodes.ACC_STATIC) != 0){
                    return new MethodVisitor(Opcodes.ASM9, super.visitMethod(access, name, descriptor, signature,
                            exceptions)) {
                        @Override
                        public void visitCode() {
                            super.visitCode();
                            // 将一个 true 值压入操作数栈
                            mv.visitInsn(Opcodes.ICONST_1);
                            // 将 int 转换为 Boolean 对象
                            mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
                            // 返回
                            mv.visitInsn(Opcodes.ARETURN);
                        }
                    };
                }
                return super.visitMethod(access, name, descriptor, signature, exceptions);
            }
        }, 0);

        byte[] modifiedBytes = classWriter.toByteArray();

        FileOutputStream outputStream = new FileOutputStream(inputFile);
        outputStream.write(modifiedBytes);
        outputStream.close();
        System.out.println("Modified class written to " + inputFile.getAbsolutePath());
    }

}
